import os
import amara

import atomixlib
atomixlib.default_engine_name = 'amara'

from amplee.storage import storepyscopg
from amplee.atompub import *
from amplee.atompub.member import EntryMember

from brightcontent.core.store import COMMON_PREFIXES, ATOM10_NS
from brightcontent.util import fixup_namespaces, quick_xml_scan

def do_import():
    doc = amara.parse(input_file_or_url, prefixes=COMMON_PREFIXES)
    envelope = amara.create_document(u"atom:feed", ns=ATOM10_NS)
    for nonentry in doc.feed.xml_xpath(u'*[not(self::atom:entry)]'):
        envelope.feed.xml_append(nonentry)

    # Right now BC's model is that the Weblog is one service with a single workspace
    service = service.AtomPubService(app_store)
    id_ = envelope.id
    title=envelope.title
    workspace = workspace.AtomPubWorkspace(service, id_, title)

    collection = collection.AtomPubCollection(
        workspace, id_, title,
        base_uri=envelope.xml:xpath('string(atom:link[@rel="self"]/@href)'))

    for entry in doc.feed.entry:
        print unicode(entry.id)
        entry = atomixlib.d_entry(content)
        member = EntryMember(collection, id=entry.id, atom=entry)
        collection.attach(member, member_content=entry)


if __name__ = '__main__':
    import sys
    input_file_or_url = sys.argv[1]
    try:
        db_connection = sys.argv[2]
    except IndexError:
        db_connection = 'dbname=brightcontent'
    do_import(input_file_or_url, db_connection)

